package com.kehutong.crm.admin;

import com.kehutong.common.IpUtils;
import com.kehutong.common.errcode.Result;
import com.kehutong.crm.service.DemandForecastSequenceService;
import com.kehutong.crm.service.DemandForecastService;
import com.kehutong.crm.worker.DemandForecastWorker;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 需求预测控制器
 *
 * @author wupengfei
 */
@MvcAction
@ReqMapping("/admin/crm/demand")
public class DemandForecastController {

    private static Logger logger = LoggerFactory.getLogger(DemandForecastController.class);

    @Inject
    private DemandForecastService demandForecastService;

    @Inject
    private DemandForecastSequenceService demandForecastSequenceService;

    // @ReqMapping("/forecast/mobile")
    public Object forecast(String mobile, String type) throws Exception {
        return demandForecastService.forecast(mobile, type);
    }

    @ReqMapping("/getByType")
    public Object getByType(JSONObject jsonObject) throws Exception {
        return demandForecastService.getByType(jsonObject);
    }

    @ReqMapping("/getByUserId")
    public Object getByUserId(String userId) throws Exception {
        return demandForecastService.getByUserId(userId);
    }

    @ReqMapping("/rearrange")
    public Object rearrange(String id) throws Exception {
        return demandForecastSequenceService.rearrange(id);
    }

    @ReqMapping("/forecastSwitch")
    public Object forecastSwitch(HttpServletRequest request, Integer isOpen) throws Exception {
        boolean hasPermission = isHasPermission(request);
        if (!hasPermission) {
            return Result.badArgument();
        }
        DemandForecastWorker.setForecastSwitch(isOpen != null && 1 == isOpen);
        return Result.success(DemandForecastWorker.isForecastSwitch());
    }

    @ReqMapping("/forecast")
    public Object forecast(HttpServletRequest request) throws Exception {
        boolean hasPermission = isHasPermission(request);
        if (!hasPermission) {
            return Result.badArgument();
        }
        return DemandForecastWorker.forecast();
    }

    private boolean isHasPermission(HttpServletRequest request) {
        String ip = IpUtils.getAddr(request);
        logger.info("访问者ip=" + ip);
        return "localhost".equals(ip) || "127.0.0.1".equals(ip);
    }

}
